//
//  OpenSDK_NumberInputView.m
//
//  Created by 涂俊 on 2018/8/10.
//

#import "OpenSDK_NumberInputView.h"

/**
 * 内部实现的用于展示数字的label
 */
@interface OpenSDK_NumberLabel : UILabel

/**位数*/
@property (nonatomic,assign)NSInteger numberLength;

/**否密文显示*/
@property (nonatomic,assign)bool secureTextEntry;

/**占位横线颜色*/
@property (nonatomic,assign)UIColor *lineColor;

@end


@implementation OpenSDK_NumberLabel

// 按照指定的格式绘制验证码/密码
- (void)drawRect:(CGRect)rect {
    //计算每位验证码/密码的所在区域的宽和高
    //    CGRect rect = CGRectMake(0,0,200,45);
    float width = rect.size.width / (float)self.numberLength;
    float height = rect.size.height;
    NSLog(@"label drawRect,width=%f,height=%f,x=%f,y=%f", width, height, rect.origin.x, rect.origin.y);
    
    // 将每位验证码/密码绘制到指定区域
    for (int i =0; i <self.text.length; i++) {
        // 计算每位验证码/密码的绘制区域
        CGRect tempRect = CGRectMake(i * width,0, width, height);
        if (self.secureTextEntry) {//密码，显示圆点
            UIImage *dotImage = [UIImage imageNamed:@"dot"];
            // 计算圆点的绘制区域
            CGPoint securityDotDrawStartPoint =CGPointMake(width * i + (width - dotImage.size.width) /2.0, (tempRect.size.height - dotImage.size.height) / 2.0);
            // 绘制圆点
            [dotImage drawAtPoint:securityDotDrawStartPoint];
        } else {//验证码，显示数字
            // 遍历验证码/密码的每个字符
            NSString *charecterString = [NSString stringWithFormat:@"%c", [self.text characterAtIndex:i]];
            // 设置验证码/密码的现实属性
            NSMutableDictionary *attributes = [[NSMutableDictionary alloc]init];
            attributes[NSForegroundColorAttributeName] = self.textColor;
            attributes[NSFontAttributeName] = self.font;
            // 计算每位验证码/密码的绘制起点（为了使验证码/密码位于tempRect的中部，不应该从tempRect的重点开始绘制）
            // 计算每位验证码/密码的在指定样式下的size
            CGSize characterSize = [charecterString sizeWithAttributes:attributes];
            CGPoint vertificationCodeDrawStartPoint = CGPointMake(width * i + (width - characterSize.width) /2.0, (tempRect.size.height - characterSize.height) /2.0);
            // 绘制验证码/密码
            [charecterString drawAtPoint:vertificationCodeDrawStartPoint withAttributes:attributes];
        }
    }
    //绘制底部横线
    for (int k = 0; k<self.numberLength; k++) {
        [self drawBottomLineWithRect:rect andIndex:k];
    }
}

static CGFloat lineHeight = 3;
//绘制占位的线条
- (void)drawBottomLineWithRect:(CGRect)rect andIndex:(int)k {
    // 已经输入字符，不画横线
    if (k < self.text.length) {
        return;
    }
    float width = rect.size.width / (float)self.numberLength;
    float height = rect.size.height;
    //1.获取上下文
    CGContextRef context =UIGraphicsGetCurrentContext();
    //2.设置当前上下文路径
    CGContextSetFillColorWithColor(context, self.lineColor.CGColor);
    
    CGRect rectangle = CGRectMake(k * width + width/4, height/2 - lineHeight/2, width / 2, lineHeight);
    CGContextFillRect(context, rectangle);
}

@end



/**
 * 封装后的，用于外部使用的InputView。
 * 内部实现实际是UITextField + OpenSDK_NumberLabel
 */
@interface OpenSDK_NumberInputView () <UITextFieldDelegate>

/**用于获取键盘输入的内容，实际不显示*/
@property (nonatomic,strong)UITextField *textField;
/**背景图片*/
@property (nonatomic,strong)UIImageView *backgroundImageView;
/**实际用于显示验证码/密码的label*/
@property (nonatomic,strong)OpenSDK_NumberLabel *label;

@end

@implementation OpenSDK_NumberInputView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initView];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        [self initView];
    }
    return self;
}

- (void)initView {
    //通过点击自身，来弹出键盘
    [self setUserInteractionEnabled:YES];
    [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showKeyBoard:)]];
    
    // 设置透明背景色，保证vertificationCodeInputView显示的frame为backgroundImageView的frame
    self.backgroundColor = [UIColor clearColor];
    /* 调出键盘的textField */
    self.textField = [[UITextField alloc] init];
    [self.textField setTranslatesAutoresizingMaskIntoConstraints:NO];
    // 隐藏textField，通过点击OpenSDK_NumberInputView使其成为第一响应者，来弹出键盘
    self.textField.hidden = YES;
    self.textField.secureTextEntry = YES;//弹出的不是第三方键盘
    self.textField.clearsOnBeginEditing = NO;
    self.textField.clearButtonMode = UITextFieldViewModeNever;
    self.textField.keyboardType = UIKeyboardTypeNumberPad;
    self.textField.delegate = self;
    // 将textField放到最上边
    [self insertSubview:self.textField atIndex:0];
    
    
    /* 添加用于显示验证码/密码的label */
    self.label = [[OpenSDK_NumberLabel alloc]init];
    [self.label setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self addSubview:self.label];
    
    // 设置验证码/密码的位数默认为四位
    [self setNumberLength: 4];
    // 设置默认字体大小
    [self setTextFont: [UIFont systemFontOfSize:18]];
    // 设置默认占位横线颜色(默认灰色)
    [self setLineColor:[UIColor lightGrayColor]];
    // 清空text
    [self clearText];
    
    // textField撑满view
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.textField attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.textField attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.textField attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.textField attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
    
    // label撑满view
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeading multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTrailing multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeTop multiplier:1.0 constant:0]];
    [self addConstraint:[NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeBottom multiplier:1.0 constant:0]];
}

- (void)setTextColor:(UIColor *)textColor {
    _textColor = textColor;
    self.label.textColor = textColor;
}

- (void)setTextFont:(UIFont *)textFont {
    _textFont = textFont;
    self.label.font = textFont;
}

- (void)setLineColor:(UIColor *)lineColor {
    _lineColor = lineColor;
    self.label.lineColor = lineColor;
}

- (void)setNumberLength:(NSInteger)numberLength {
    _numberLength = numberLength;
    self.label.numberLength = numberLength;
}

- (void)setSecureTextEntry:(BOOL)secureTextEntry {
    _secureTextEntry = secureTextEntry;
    self.label.secureTextEntry = secureTextEntry;
}

- (void)setBackgroudImage:(UIImage *)backgroundImage {
    if (!backgroundImage) {
        return;
    }
    if (!self.backgroundImageView) {
        self.backgroundImageView = [[UIImageView alloc]initWithFrame:self.bounds];
        // 将背景图片插入到label的后边，避免遮挡验证码/密码的显示
        [self insertSubview:self.backgroundImageView belowSubview:self.label];
    }
    self.backgroundImageView.image = backgroundImage;
}

#pragma mark - public api
- (void)becomeFirstResponder {
    [self.textField becomeFirstResponder];
}

- (void)clearText {
    self.textField.text = @"";
    self.label.text = @"";
}

#pragma mark - 点击自身的响应，弹出键盘
- (void)showKeyBoard:(id)sender {
    [self.textField becomeFirstResponder];
}

#pragma mark - TextField的回调
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *updatedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    // 判断验证码/密码的位数是否达到预定的位数
    if (updatedString.length <= self.numberLength) {
        textField.text = updatedString;
        self.label.text = updatedString;
        if (updatedString.length == self.numberLength) {
            if (self.completeCallback) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.textField endEditing:YES];
                    self.completeCallback(self.label.text);
                });
            }
        }
    }
    //回调外部delegate的shouldChangeCharactersInRange
    if (self.delegate && [self.delegate respondsToSelector:@selector(textField:shouldChangeCharactersInRange:replacementString:)]) {
        [self.delegate textField:textField shouldChangeCharactersInRange:range replacementString:string];
    }
    return NO;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (self.delegate && [self.delegate respondsToSelector:@selector(textFieldDidBeginEditing:)]) {
        [self.delegate textFieldDidBeginEditing:textField];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.delegate && [self.delegate respondsToSelector:@selector(textFieldDidEndEditing:)]) {
        [self.delegate textFieldDidEndEditing:textField];
    }
}

@end
